<?php

namespace App\Http\Controllers\Innerend;


use App\Models\ArticleComment;
use App\Models\News;
use App\Models\NewsCate;
use App\Models\NewsDesc;
use App\Models\NewsTopic;
use App\Models\SiteCate;
use App\Models\Topic;
use App\Models\TopicCate;
use App\Models\User;
use App\Service\Tree;
use Illuminate\Support\Facades\DB;

class FangtanController extends BaseController
{
    // 新闻文章

    protected $list_cache = true;

    public function initialize()
    {
        parent::initialize();

        $this->model = 'Fangtan';
    }

    // 父级
    // 添加，修改，删除，列表，停用 操作

    // 列表数据展示
    protected function listTable($lists)
    {
        // 整理
        $is_online = $this->getData('is_online', 0, 'intval');
        $trList    = [];
        if(empty($lists)){
            return ['list' => $lists, 'tr' => $trList];
        }

        // 展示列表表格
        $listHtml = $this->adminList();
        foreach($lists as $key => $item){
            // 数据
            $_id = $item['id'];
            // 操作
            $param   = ['fangtan_id' => $_id, 'is_online' => $is_online];
            $operate = $listHtml->operate_list($param, '访谈用户', '/fangtan-user/lists');
            if($is_online){
                $operate .= $listHtml->operate_list($param, '用户预约', '/fangtan-appoint/lists');
                $operate .= $listHtml->operate_list(['fangtan_id' => $_id, 'channel' => 'answer'], '访谈问答', '/fangtan-fresh/lists');
                $operate .= $listHtml->operate_list(['fangtan_id' => $_id, 'channel' => 'interview'], '访谈内容', '/fangtan-fresh/lists');
            } else{
                $operate .= $listHtml->operate_list($param, '用户报名', '/fangtan-appoint/lists');
            }
            $operate .= $listHtml->operate_edit(['id' => $_id, 'is_online' => $is_online], '编辑');
            $operate .= $listHtml->operate_soft_delete(['id' => $_id, 'is_online' => $is_online], '你确定要删除该文章吗？');

            // 图片
            $imageHtml = '';
            if($item['cover']){
                $image     = $this->getFullUrl($this->showQiniuImage($item['cover'], 100, 100));
                $imageHtml = "<img src='".$image."' style='width:100px;' >";
            }

            // 页面
            $tr = $listHtml->list_check($item['id']);
            $tr .= $listHtml->list_td($item['title']);
            $tr .= $listHtml->list_td($imageHtml);
            // 如果是线下活动
            if(empty($is_online)){
                $tr .= $listHtml->list_td($item['address']);
                $tr .= $listHtml->list_td($item['number']);
            }
            $tr .= $listHtml->list_td(date('Y-m-d H:i', $item['start_time']));
            $tr .= $listHtml->list_td(date('Y-m-d H:i', $item['end_time']));
            $tr .= $listHtml->list_td(date('Y-m-d H:i', $item['ctime']));
            $tr .= $listHtml->list_td($operate);
            $tr .= $operate;

            // 整合
            $trList[] = $listHtml->list_tr($tr);
        }

        // 整合
        return ['list' => $lists, 'tr' => $trList];
    }

    // 列表字段
    protected function list_fields()
    {
        $is_online = $this->getData('is_online', 0, 'intval');
        if($is_online){
            $field = ['title' => ['主题', 250], 'cover' => ['封面', 80], 'start_time' => ['开始时间', 120], 'end_time' => ['结束时间', 120], 'ctime' => ['创建时间', 120], 'operate' => ['操作', 250],];
        } else{
            $field = ['title' => ['主题', 250], 'cover' => ['封面', 80], 'address' => '访谈地址', 'number' => '人数', 'start_time' => ['开始时间', 120], 'end_time' => ['结束时间', 120], 'ctime' => ['创建时间', 120], 'operate' => ['操作', 250],];
        }

        return $field;
    }

    // 列表搜索
    protected function list_search()
    {
        $request = $this->getData();
        $form    = $this->adminList();
        $keyword = $form->formInput('keyword', $request['keyword'] ?? '', '关键字');
        $datemin = $form->formDateTime('datemin', $request['datemin'] ?? '', '开始时间', 'datetime');
        $datemax = $form->formDateTime('datemax', $request['datemax'] ?? '', '结束时间', 'datetime');

        $search = ['keyword' => $keyword, 'datemin' => $datemin, 'datemax' => $datemax,];  // 'is_top' => $is_top,
        $this->assign('search', $search);

        $searchHide = ['is_online'];
        $this->assign('searchHide', $searchHide);
    }

    // 列表顶部按钮
    protected function listTopButton()
    {
        $is_online  = $this->getData('is_online', 0, 'intval');
        $title      = $is_online ? '线上直播' : '线下活动';
        $addUrl     = url('/innerend/'.$this->controller.'/add?is_online='.$is_online);
        $top_button = '<a href="javascript:;" onclick="onEdit(\''.$addUrl.'\')" class="btn btn-success radius">'.$title.'</a> ';
        $this->assign('top_button', $top_button);
    }

    // 表单页面
    protected function formTable()
    {
        $html   = '';
        $info   = $this->onShow();
        $form   = $this->adminForm();
        $hosts  = $info['host'] ?? [];
        $guests = $info['guest'] ?? [];
        if(!empty($info['info'])){
            $info = is_object($info['info']) ? $info['info']->toArray() : $info['info'];
        }

        $_online    = $this->getData('is_online', 0, 'intval');
        $start_time = empty($info['start_time']) ? '' : date('Y-m-d H:i:s', $info['start_time']);
        $end_time   = empty($info['end_time']) ? '' : date('Y-m-d H:i:s', $info['end_time']);
        // 封面图片
        $title       = $form->formInput('title', $info['title'] ?? '', '主题');
        $cover       = $form->formImage('cover', $info['uid'] ?? '');
        $start_time  = $form->formDateTime('start_time', $start_time, '开始时间', 'datetime');
        $end_time    = $form->formDateTime('end_time', $end_time, '结束时间', 'datetime');
        $latitude    = $form->formInput('latitude', $info['latitude'] ?? '', '纬度');
        $longitude   = $form->formInput('longitude', $info['longitude'] ?? '', '经度');
        $address     = $form->formInput('longitude', $info['address'] ?? '', '访谈地址');
        $number      = $form->formInput('number', $info['number'] ?? '', '人数');
        $description = $form->formTextarea('description', $info['description'] ?? '');
        $_id         = $form->formHidden('id', $info['id'] ?? '');
        $is_online   = $form->formHidden('is_online', $info['is_online'] ?? $_online);
        $host        = $form->ajaxSearchList2('host', $hosts, 'User', 'id', 'username');
        $guest       = $form->ajaxSearchList2('guest', $guests, 'User', 'id', 'username');
        //$content     = $form->formUeditor('content', $info['content'] ?? '');

        $html .= $form->makeItem('标题', $title);
        $html .= $form->makeItem('封面图片', $cover);
        $html .= $form->makeItem('开始时间', $start_time);
        $html .= $form->makeItem('结束时间', $end_time);
        if(empty($_online)){
            $html .= $form->makeItem('纬度', $latitude);
            $html .= $form->makeItem('经度', $longitude);
            $html .= $form->makeItem('访谈地址', $address);
            $html .= $form->makeItem('人数', $number);
        }

        $html .= $form->makeItem('主持人', $host);
        $html .= $form->makeItem('嘉宾', $guest);
        $html .= $form->makeItem('描述', $description);
        //$html .= $form->makeItem('内容', $content);
        $html .= $is_online;
        $html .= $_id;

        return $html;
    }

    // 软删除
    public function onSoft()
    {
        $this->throwIf(empty($this->id), '请指定删除记录');

        $where  = ['id' => $this->id];
        $model  = $this->checkModel($this->model);
        $result = $model->isCache(true)->softDelete($where);
        $this->throwIf($result === false, $model->getError());

        return $this->success();
    }

    // 列表查询
    protected function listWhere()
    {
        $keyword = $this->getData('keyword', null, 'trim');
        $isLine  = $this->getData('is_online', 1, 'intval');
        $where   = [['verify', '=', 1], ['is_online', '=', $isLine]];
        if($keyword){
            $where[] = $this->orWhere('title|description', 'like', $keyword);
            // 不在缓存
            $this->list_cache = false;
        }

        // 时间筛选
        $startTime = $this->getData('datemin', '', 'trim');
        $endTime   = $this->getData('datemax', '', 'trim');
        if($startTime){
            $where[] = ['start_time', '>=', strtotime($startTime)];
        }
        if($endTime){
            $where[] = ['start_time', '<=', strtotime($endTime)];
        }


        return $where;
    }

    // 添加
    protected function _before_add()
    {
        $data = [
            // 'id'          => $this->getData("id"),
            'title'       => $this->getData("title", null, 'trim'),
            'cover'       => $this->getData("cover", null, 'trim'),
            'description' => $this->getData("description", null, 'trim'),
            'start_time'  => $this->getData("start_time", 0, 'strtotime'),
            'end_time'    => $this->getData("end_time", 0, 'strtotime'),
            'is_online'   => $this->getData("is_online", 0, 'intval'),
            'address'     => $this->getData("address", null, 'trim'),
            'latitude'    => $this->getData("latitude", 0, 'trim'),
            'longitude'   => $this->getData("longitude", 0, 'trim'),
            'number'      => $this->getData("number", 0, 'intval'),
            'power'       => $this->getData("power", 'all', 'trim'),
            'verify'      => 1,
            //'host'        => $this->getData("host", [], 'is_array'),
            //'guest'       => $this->getData("guest", [], 'is_array'),
            // 'is_over'     => $this->getData("is_over", 0, 'intval'),
            // 'ctime'       => $this->getData("ctime", 0, 'intval'),
            // 'mtime'       => $this->getData("mtime", 0, 'intval'),
        ];

        $host  = $this->getData("host", '', 'trim');
        $guest = $this->getData("guest", '', 'trim');
        // 组合
        $data['host']  = $host ? explode(',', $host) : [];
        $data['guest'] = $guest ? explode(',', $guest) : [];
        // 线上访谈
        $this->throwReturn($data['end_time'] <= $data['start_time'], '结束时间不能小于开始时间！');
        if($data['is_online'] == 1){
            $this->throwReturn(!in_array($data['power'], ['all', 'auth', 'no_auth']), '权限值错误！');
            $this->throwReturn(empty($data['host']), '请指定主持人！');
            $this->throwReturn(empty($data['guest']), '请指定嘉宾！');
            $this->throwReturn(count($data['guest']) != count($data['guest'], 1), '嘉宾数据错误！');
            $this->throwReturn(count($data['host']) != count($data['host'], 1), '主持人数据错误！');
            // 主持人只能一个
            $this->throwReturn(count($data['host']) != 1, '主持人有且只有一个人！');
            // 主持人和嘉宾不能是同一个人
            $user = array_intersect($data['host'],$data['guest']);
            $this->throwReturn($user, '主持人和嘉宾不能是同一个人！');
        } else{
            // 线下活动
            $this->throwReturn(empty($data['address']), '线下访谈，请指定参加地址！');
            $this->throwReturn(empty($data['latitude']), '线下访谈，请指定纬度！');
            $this->throwReturn(empty($data['longitude']), '线下访谈，请指定经度！');
        }

        // TODO 审核
        $this->baiduTextCensor($data['title'].$data['description']);

        return $data;
    }

    // 修改
    protected function _before_edit()
    {
        $data  = [
            'title'       => $this->getData("title", null, 'trim'),
            'cover'       => $this->getData("cover", null, 'trim'),
            'description' => $this->getData("description", null, 'trim'),
            'start_time'  => $this->getData("start_time", 0, 'strtotime'),
            'end_time'    => $this->getData("end_time", 0, 'strtotime'),
            'is_online'   => $this->getData("is_online", 0, 'intval'),
            'address'     => $this->getData("address", null, 'trim'),
            'latitude'    => $this->getData("latitude", 0, 'trim'),
            'longitude'   => $this->getData("longitude", 0, 'trim'),
            'number'      => $this->getData("number", 0, 'intval'),
            'power'       => $this->getData("power", 'all', 'trim'),
            'verify'      => 1,
            //'host'        => $this->getData("host", [], 'trim'),
            //'guest'       => $this->getData("guest", [], 'trim'),
        ];
        $host  = $this->getData("host", '', 'trim');
        $guest = $this->getData("guest", '', 'trim');
        // 组合
        $data['host']  = $host ? json_decode($host, true) : [];
        $data['guest'] = $guest ? json_decode($guest, true) : [];

        // 线上访谈
        $this->throwReturn($data['end_time'] <= $data['start_time'], '结束时间不能小于开始时间！');
        if($data['is_online'] == 1){
            $this->throwReturn(!in_array($data['power'], ['all', 'auth', 'no_auth']), '权限值错误！');
            $this->throwReturn(empty($data['host']), '请指定主持人！');
            $this->throwReturn(empty($data['guest']), '请指定嘉宾！');
            $this->throwReturn(count($data['guest']) != count($data['guest'], 1), '嘉宾数据错误！');
            $this->throwReturn(count($data['host']) != count($data['host'], 1), '主持人数据错误！');
            // 主持人只能一个
            $this->throwReturn(count($data['host']) != 1, '主持人有且只有一个人！');
            // 主持人和嘉宾不能是同一个人
            $user = array_intersect($data['host'],$data['guest']);
            $this->throwReturn($user, '主持人和嘉宾不能是同一个人！');
        } else{
            // 线下活动
            $this->throwReturn(empty($data['address']), '线下访谈，请指定参加地址！');
            $this->throwReturn(empty($data['latitude']), '线下访谈，请指定纬度！');
            $this->throwReturn(empty($data['longitude']), '线下访谈，请指定经度！');
        }

        // TODO 审核
        $this->baiduTextCensor($data);

        return $data;
    }

}


